package com.hs.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hs.entity.dto.PositionDTO;
import com.hs.entity.dto.TrendDTO;
import com.hs.entity.pojo.*;
import com.hs.entity.vo.PageVO;
import com.hs.entity.vo.TrendDetailVO;
import com.hs.entity.vo.TrendSearchVO;
import com.hs.entity.vo.UserTrendVO;
import com.hs.service.*;
import com.hs.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hs
 * @since 2023-08-05
 */
@RestController
@RequestMapping("/trend")
@Api(tags = "动态")
public class TrendController {

    @Resource
    private TrendService trendService;

    @Resource
    private TrendImageService trendImageService;

    @Resource
    private ImageService imageService;

    @Resource
    private UserService userService;

    @Resource
    private TrendCollectService trendCollectService;

    @Resource
    private RedisCache redisCache;

    @Value("${position.key}")
    private String positionKey;


    @GetMapping
    @ApiOperation("分页查询动态")
    public ResultResponse<PageVO> getTrends(@RequestParam(required = false,defaultValue = "1") Integer pageNum,HttpServletRequest request) {
        return trendService.getTrends(pageNum,request);
    }

    @GetMapping("/{id}")
    @ApiOperation("获取动态详情信息")
    public ResultResponse<TrendDetailVO> getTrendDetail(@PathVariable Integer id) {
        Trend trend = Optional.ofNullable(trendService.getById(id)).orElseGet(Trend::new);
        Integer userId = trend.getUserId();
        User user = Optional.ofNullable(userService.getById(userId)).orElseGet(User::new);

        List<Integer> imageIds = trendImageService.query().eq("trend_id", id).list().stream().map(TrendImage::getImageId).collect(Collectors.toList());
        List<String> imageUrls;
        if (imageIds.isEmpty()){
            imageUrls = Collections.emptyList();
        }else {
            imageUrls = imageService.query().in("id", imageIds).list().stream().map(Image::getUrl).collect(Collectors.toList());
        }

        TrendDetailVO trendDetailVO = BeanCopyUtil.copyBean(trend, TrendDetailVO.class);
        trendDetailVO.setImages(imageUrls);
        trendDetailVO.setHead(user.getHead());
        trendDetailVO.setArea(user.getArea());
        trendDetailVO.setNickName(user.getNickName());

        // 查询一下用户当前收藏状态
        Integer currentUserId = SecurityUserHolder.getUserId();
        if (Objects.nonNull(currentUserId)){
            LambdaQueryWrapper<TrendCollect> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TrendCollect::getUserId,currentUserId).eq(TrendCollect::getTrendId,id);
            trendDetailVO.setCollectFlag(trendCollectService.count(queryWrapper)>0);
        }

        return ResultResponse.ok(trendDetailVO);
    }

    @GetMapping("/address")
    @ApiOperation("粗略获取用户地理位置")
    public ResultResponse<?> getAddress(HttpServletRequest request) {
        // 先去redis中获取，若没有则是远程调用接口
        Integer userId = SecurityUserHolder.getUserId();
        PositionDTO address = redisCache.getCacheObject("pet:view:position:" + userId);

        if (Objects.isNull(address)) {
            String ipAddress = IpUtil.getIpAddr(request);
            RestTemplate restTemplate = new RestTemplate();
            address = restTemplate.getForObject("https://apis.map.qq.com/ws/location/v1/ip?ip="+ipAddress+"&key="+positionKey, PositionDTO.class);
            // =375 说明在局域网内
            if (address.getStatus() != 375) {
                redisCache.setCacheObject("pet:view:position:" + userId,address,12, TimeUnit.HOURS);
            }
        }
        return ResultResponse.ok(address);
    }

    @PostMapping("/publish")
    @ApiOperation("发布动态")
    public ResultResponse<?> publishTrend(@RequestBody TrendDTO trendDTO){
        return trendService.publishTrend(trendDTO);
    }

    @PostMapping("/like")
    @ApiOperation("动态点赞")
    public ResultResponse<?> likeTrend(@RequestParam Integer trendId,@RequestParam @ApiParam("点赞状态：false表示未点赞，true表示已点赞") Boolean flag){
        return trendService.likeTrend(trendId,flag);
    }

    @PostMapping("/collect")
    @ApiOperation("动态收藏")
    public ResultResponse<?> collectTrend(@RequestParam Integer trendId,@RequestParam @ApiParam("收藏状态：false表示未收藏，true表示已收藏") Boolean flag){
        return trendService.collectTrend(trendId,flag);
    }

    @GetMapping("/likedTrends")
    @ApiOperation("获取我点赞的动态")
    public ResultResponse<List<UserTrendVO>> getMyLikeTrends(){
        return trendService.getMyLikeTrends();
    }

    @GetMapping("/collectedTrends")
    @ApiOperation("获取我收藏的动态")
    public ResultResponse<List<UserTrendVO>> getMyCollectTrends(){
        return trendService.getMyCollectTrends();
    }

    @GetMapping("/tagTrends/{tagId}")
    @ApiOperation("根据标签ID分页查询动态")
    public ResultResponse<PageVO> getTrendsByTagId(@RequestParam Integer pageNum,@PathVariable Integer tagId){
        return trendService.getTrendsByTagId(pageNum,tagId);
    }

    @GetMapping("/search/{keyword}/{pageIndex}/{pageSize}")
    @ApiOperation("搜索动态并且高亮显示")
    public ResultResponse<List<Map<String, Object>>> searchTrendsHighlight(@PathVariable("keyword") String keyword,
                                                                           @PathVariable("pageIndex") Integer pageIndex,
                                                                           @PathVariable("pageSize") Integer pageSize) throws IOException {
        return trendService.searchTrendsHighlight(keyword,pageIndex,pageSize);
    }

}

